package com.mallcai.bigdata.ladon.service.report.impl.handler;

import com.cake.bigdata.starter.exception.category.BusinessException;
import com.mallcai.bigdata.ladon.service.report.impl.ReportQueryContext;
import com.mallcai.bigdata.ladon.service.report.impl.ReportQueryParamHolder;
import com.mallcai.bigdata.ladon.utils.CollectionUtils;
import com.mallcai.bigdata.ladon.utils.SqlUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Map;
import java.util.Set;

/**
 * @author feixy
 * @version 1.0
 * @date 2019-07-20 14:56
 */
@Component
@Order(5000)
public class CheckNotNullSqlParamNameHandler extends AbstractReportQueryPreHandler {


    @Override
    public void preInternal(ReportQueryContext context) {
        String sql = context.getSql();
        Set<String> paramNames = SqlUtils.parseUniqueParamName(sql);
        // 传递的数据库去的参数一定不能为空
        if(CollectionUtils.isNotEmpty(paramNames)){
            Map<String, ReportQueryParamHolder> queryParams = context.getQueryParams();
            for (String paramName : paramNames) {
                ReportQueryParamHolder reportQueryParamHolder = queryParams.get(paramName);
                if (reportQueryParamHolder == null || reportQueryParamHolder.getValue() == null){
                    throw new BusinessException(String.format("非法的参数:参数[%s]的值未设置", paramName));
                }
                Object value = reportQueryParamHolder.getValue();
                if (CollectionUtils.isCollection(value)){
                    if (((Collection)value).size() == 0){
                        throw new BusinessException(String.format("非法的参数:参数[%s]的值不能为空数组", paramName));
                    }
                }

            }
        }
    }
}
